<?php 
namespace Cmf\Models;
/**
* 树形结构数据存取
*/
class Tree extends \Phalcon\Mvc\Model
{	
	/**
	 * 将返回的数据集转换成树形结构
	 * @param  array   $list  [要转换的数据集]
	 * @param  string  $pk    [数据标记字段]
	 * @param  string  $pid   [数据父分类标记字段]
	 * @param  string  $child [数据子分类标记字段]
	 * @param  integer $root  [要进行转换的分类]
	 * @return array   $tree  [返回树形结果集]
	 */
	static public function listToTree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0){
		// 创建Tree
	    $tree = array();
	    if(is_array($list)) {

	        // 创建基于主键的数组引用
	        $refer = array();
	        foreach ($list as $key => $data) {
	            $refer[$data[$pk]] =& $list[$key];
	        }
	        foreach ($list as $key => $data) {
	            // 判断是否存在parent
	            $parentId =  $data[$pid];
	            if ($root == $parentId) {
	                $tree[] =& $list[$key];
	            }else{
	                if (isset($refer[$parentId])) {
	                    $parent =& $refer[$parentId];
	                    $parent[$child][] =& $list[$key];
	                }
	            }
	        }
	    }
	    return $tree;
	}

	/**
	 * 格式树形数据结构
	 * @param  array   $list  		[树形结构结果集]
	 * @param  integer $level 		[进行递归时使用的参数]
	 * @param  string  $title 		[树形结构名称]
	 * @return array   $formatTree  [格式化树形结构数据集]
	 */
	static private $formatTree; //用于树型数组完成递归格式的全局变量
	static private function _toFormatTree($list,$level=0,$title = 'title') {
		foreach($list as $key=>$val){
			$tmp_str=str_repeat("&nbsp;",$level*2);
			$tmp_str.="└";

			$val['level'] = $level;
			$val['title_show'] =$level==0?$val[$title]."&nbsp;":$tmp_str.$val[$title]."&nbsp;";

			if(!array_key_exists('_child',$val)){
				array_push(self::$formatTree,$val);
			}else{
				$tmp_ary = $val['_child'];
				unset($val['_child']);
				array_push(self::$formatTree,$val);
				self::_toFormatTree($tmp_ary,$level+1,$title); //进行下一层递归
			}
		}
			return;
	}

	static public function toFormatTree($list,$title = 'title',$pk='id',$pid = 'pid',$root = 0){
		$list = self::listToTree($list,$pk,$pid,'_child',$root);
		self::$formatTree = array();
		self::_toFormatTree($list,0,$title);
		return self::$formatTree;
	}
}
